<template>
  <div class="product-detail">
    <div v-if="product" class="detail-content">
      <!-- 商品基本信息 -->
      <div class="detail-section">
        <h3>商品基本信息</h3>
        <div class="product-header">
          <div class="product-image">
            <img :src="product.productImage || product.image || '/default-product.png'" :alt="product.productName || product.name">
          </div>
          <div class="product-info">
            <h2 class="product-name">{{ product.productName || product.name || '未命名商品' }}</h2>
            <div class="product-meta">
              <span class="product-code">编码: {{ product.productCode || product.code || '无编码' }}</span>
              <span v-if="product.skuCode" class="product-sku">SKU: {{ product.skuCode }}</span>
            </div>
            <div class="product-status">
              <span class="status" :class="(product.status || '').toLowerCase()">
                {{ getStatusText(product.status) }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 价格信息 -->
      <div class="detail-section">
        <h3>价格信息</h3>
        <div class="info-grid">
          <div class="info-item">
            <label>零售价格</label>
            <span class="retail-price">¥{{ (product.retailPrice || 0).toFixed(2) }}</span>
          </div>
          <div class="info-item">
            <label>会员价格</label>
            <span class="member-price">¥{{ (product.memberPrice || 0).toFixed(2) }}</span>
          </div>
          <div class="info-item">
            <label>成本价格</label>
            <span class="cost-price">¥{{ (product.costPrice || 0).toFixed(2) }}</span>
          </div>
          <div class="info-item">
            <label>积分比例</label>
            <span>{{ ((product.pointsRatio || 0) * 100).toFixed(1) }}%</span>
          </div>
        </div>
      </div>

      <!-- 库存信息 -->
      <div class="detail-section">
        <h3>库存信息</h3>
        <div class="info-grid">
          <div class="info-item">
            <label>当前库存</label>
            <span class="stock-quantity">{{ product.currentStock || product.stock || 0 }} {{ product.stockUnit || '件' }}</span>
          </div>
          <div class="info-item">
            <label>最低库存</label>
            <span>{{ product.minStock }} {{ product.stockUnit || '件' }}</span>
          </div>
          <div class="info-item">
            <label>最高库存</label>
            <span>{{ product.maxStock }} {{ product.stockUnit || '件' }}</span>
          </div>
          <div class="info-item">
            <label>库存状态</label>
            <span class="stock-status" :class="getStockStatusClass(product.currentStock || product.stock || 0, product.minStock)">
              {{ getStockStatusText(product.currentStock || product.stock || 0, product.minStock) }}
            </span>
          </div>
        </div>
      </div>

      <!-- 商品属性 -->
      <div class="detail-section">
        <h3>商品属性</h3>
        <div class="info-grid">
          <div class="info-item">
            <label>是否序列化</label>
            <span class="attribute" :class="product.isSerialized ? 'yes' : 'no'">
              {{ product.isSerialized ? '是' : '否' }}
            </span>
          </div>
          <div class="info-item">
            <label>是否赠品</label>
            <span class="attribute" :class="product.isGift ? 'yes' : 'no'">
              {{ product.isGift ? '是' : '否' }}
            </span>
          </div>
          <div class="info-item">
            <label>商品分类</label>
            <span>{{ product.categoryName || '未分类' }}</span>
          </div>
          <div class="info-item">
            <label>创建时间</label>
            <span>{{ formatDate(product.createdAt) }}</span>
          </div>
        </div>
      </div>

      <!-- 商品描述 -->
      <div v-if="product.description" class="detail-section">
        <h3>商品描述</h3>
        <div class="description-content">
          {{ product.description }}
        </div>
      </div>

      <!-- 商品规格 -->
      <div v-if="product.specifications" class="detail-section">
        <h3>商品规格</h3>
        <div class="specifications-content">
          {{ product.specifications }}
        </div>
      </div>

      <!-- 销售统计 -->
      <div class="detail-section">
        <h3>销售统计</h3>
        <div class="sales-stats">
          <div class="stat-item">
            <div class="stat-value">{{ salesStats.totalSales }}</div>
            <div class="stat-label">总销量</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">¥{{ (salesStats.totalRevenue || 0).toFixed(2) }}</div>
            <div class="stat-label">总销售额</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ salesStats.monthlySales }}</div>
            <div class="stat-label">本月销量</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">¥{{ (salesStats.monthlyRevenue || 0).toFixed(2) }}</div>
            <div class="stat-label">本月销售额</div>
          </div>
        </div>
      </div>

      <!-- 库存变动记录 -->
      <div class="detail-section">
        <h3>库存变动记录</h3>
        <div class="inventory-history">
          <div v-for="(record, index) in inventoryHistory" :key="index" class="history-item">
            <div class="history-icon" :class="record.type">
              <i :class="getHistoryIcon(record)"></i>
            </div>
            <div class="history-content">
              <div class="history-title">{{ record.description }}</div>
              <div class="history-details">
                <span class="quantity-change" :class="record.type">
                  {{ record.type === 'in' ? '+' : '-' }}{{ record.quantity }}
                </span>
                <span class="history-time">{{ formatDateTime(record.timestamp) }}</span>
                <div v-if="record.reason" class="history-reason">{{ record.reason }}</div>
                <div v-if="record.operator" class="history-operator">{{ record.operator }}</div>
              </div>
            </div>
            <div class="history-balance">
              余额: {{ record.balance }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'

export default {
  name: 'ProductDetailView',
  props: {
    product: {
      type: Object,
      required: true
    }
  },
  setup(props) {
    const salesStats = ref({
      totalSales: 0,
      totalRevenue: 0,
      monthlySales: 0,
      monthlyRevenue: 0
    })
    
    const inventoryHistory = ref([])
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statuses = {
        'Active': '启用',
        'Inactive': '禁用'
      }
      return statuses[status] || status
    }
    
    // 获取库存状态文本
    const getStockStatusText = (stock, minStock) => {
      if (stock === 0) return '缺货'
      if (stock <= minStock) return '低库存'
      return '正常'
    }
    
    // 获取库存状态样式类
    const getStockStatusClass = (stock, minStock) => {
      if (stock === 0) return 'out'
      if (stock <= minStock) return 'low'
      return 'normal'
    }
    
    // 获取历史记录图标
    const getHistoryIcon = (record) => {
      // 如果后端返回了icon字段，直接使用
      if (record.icon) {
        return record.icon
      }
      // 否则根据type字段返回默认图标
      const icons = {
        'in': 'fas fa-plus',
        'out': 'fas fa-minus',
        'adjust': 'fas fa-edit'
      }
      return icons[record.type] || 'fas fa-info'
    }
    
    // 格式化日期
    const formatDate = (date) => {
      return new Date(date).toLocaleDateString('zh-CN')
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return ''
      // 处理日期格式，如果是只有日期的字符串，添加时间
      let dateStr = dateTime
      if (typeof dateTime === 'string' && dateTime.length === 10) {
        dateStr = dateTime + 'T00:00:00'
      }
      return new Date(dateStr).toLocaleString('zh-CN')
    }
    
    // 加载销售统计
    const loadSalesStats = async () => {
      try {
        const response = await fetch(`/api/retail/products/${props.product.id}/sales-stats`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          salesStats.value = {
            totalSales: data.totalSales || 0,
            totalRevenue: data.totalRevenue || 0,
            monthlySales: data.monthlySales || 0,
            monthlyRevenue: data.monthlyRevenue || 0
          }
        } else {
          console.error('加载销售统计失败:', response.statusText)
          // 如果API调用失败，使用默认值
          salesStats.value = {
            totalSales: 0,
            totalRevenue: 0,
            monthlySales: 0,
            monthlyRevenue: 0
          }
        }
      } catch (error) {
        console.error('加载销售统计失败:', error)
        // 如果API调用失败，使用默认值
        salesStats.value = {
          totalSales: 0,
          totalRevenue: 0,
          monthlySales: 0,
          monthlyRevenue: 0
        }
      }
    }
    
    // 加载库存变动记录
    const loadInventoryHistory = async () => {
      try {
        const response = await fetch(`/api/retail/products/${props.product.id}/inventory-history`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          inventoryHistory.value = data || []
        } else {
          console.error('加载库存变动记录失败:', response.statusText)
          // 如果API调用失败，使用空数组
          inventoryHistory.value = []
        }
      } catch (error) {
        console.error('加载库存变动记录失败:', error)
        // 如果API调用失败，使用空数组
        inventoryHistory.value = []
      }
    }
    
    onMounted(() => {
      loadSalesStats()
      loadInventoryHistory()
    })
    
    return {
      salesStats,
      inventoryHistory,
      getStatusText,
      getStockStatusText,
      getStockStatusClass,
      getHistoryIcon,
      formatDate,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.product-detail {
  max-width: 1000px;
  margin: 0 auto;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.detail-section {
  background: #f8fafc;
  border-radius: 8px;
  padding: 24px;
}

.detail-section h3 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e2e8f0;
}

.product-header {
  display: flex;
  gap: 24px;
  align-items: flex-start;
}

.product-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  background: white;
  border: 1px solid #e2e8f0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 1.5rem;
  font-weight: 700;
  color: #2d3748;
  margin-bottom: 8px;
}

.product-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
}

.product-code,
.product-sku {
  font-size: 0.875rem;
  color: #718096;
}

.product-status {
  margin-top: 8px;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875rem;
  font-weight: 500;
}

.status.active {
  background: #c6f6d5;
  color: #22543d;
}

.status.inactive {
  background: #fed7d7;
  color: #742a2a;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item label {
  font-weight: 500;
  color: #4a5568;
  font-size: 0.875rem;
}

.info-item span {
  color: #2d3748;
  font-size: 0.875rem;
}

.retail-price {
  font-weight: 600;
  color: #2d3748;
  font-size: 1.1rem;
}

.member-price {
  font-weight: 500;
  color: #43e97b;
}

.cost-price {
  font-weight: 500;
  color: #718096;
}

.stock-quantity {
  font-weight: 600;
  color: #2d3748;
  font-size: 1.1rem;
}

.stock-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875rem;
  font-weight: 500;
}

.stock-status.normal {
  background: #c6f6d5;
  color: #22543d;
}

.stock-status.low {
  background: #fef5e7;
  color: #744210;
}

.stock-status.out {
  background: #fed7d7;
  color: #742a2a;
}

.attribute {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875rem;
  font-weight: 500;
}

.attribute.yes {
  background: #c6f6d5;
  color: #22543d;
}

.attribute.no {
  background: #e2e8f0;
  color: #4a5568;
}

.description-content,
.specifications-content {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 16px;
  color: #2d3748;
  line-height: 1.5;
}

.sales-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

.stat-item {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 16px;
  text-align: center;
}

.stat-value {
  font-size: 1.5rem;
  font-weight: 700;
  color: #2d3748;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 0.875rem;
  color: #718096;
}

.inventory-history {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
}

.history-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}

.history-icon.in {
  background: #48bb78;
}

.history-icon.out {
  background: #f56565;
}

.history-icon.adjust {
  background: #ed8936;
}

.history-content {
  flex: 1;
}

.history-title {
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 4px;
}

.history-details {
  display: flex;
  gap: 12px;
  font-size: 0.875rem;
  color: #718096;
}

.quantity-change {
  font-weight: 500;
}

.quantity-change.in {
  color: #48bb78;
}

.quantity-change.out {
  color: #f56565;
}

.quantity-change.adjust {
  color: #ed8936;
}

.history-balance {
  font-size: 0.875rem;
  color: #4a5568;
  font-weight: 500;
}

.history-reason {
  font-size: 0.75rem;
  color: #718096;
  margin-top: 4px;
  font-style: italic;
}

.history-operator {
  font-size: 0.75rem;
  color: #4a5568;
  margin-top: 2px;
}

@media (max-width: 768px) {
  .product-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .product-image {
    width: 100px;
    height: 100px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .sales-stats {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .history-item {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}
</style>
